package com.itheima.security.springmvc.interceptor;

import com.itheima.security.springmvc.model.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 *
 * </p>
 *
 * @author flyduck
 * @since 2023/11/18
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    //调用方法之前执行->校验请求的url是否在用户的权限范围内
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //取出用户身份信息
        Object userObj = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);

        //没有认证，提示登录
        if (userObj == null) {
            writeContent(response, "请登录");
        }

        //校验请求的url是否在用户的权限范围内
        UserDto userDto = (UserDto) userObj;
        String requestURI = request.getRequestURI();
        if (userDto.getAuthorities().contains("p1") && requestURI.contains("/r/r1")) {
            return true;
        }
        if (userDto.getAuthorities().contains("p2") && requestURI.contains("/r/r2")) {
            return true;
        }
        writeContent(response, "没有权限，拒绝访问");
        return false;
    }

    //响应输出
    private void writeContent(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("text/html;charset=utf8");
        PrintWriter writer = response.getWriter();
        writer.print(msg);
        writer.close();
        response.resetBuffer();
    }
}
